package com.xuecheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.execption.XueChengPlusException;
import com.xuecheng.mapper.CourseBaseMapper;
import com.xuecheng.mapper.CourseMarketMapper;
import com.xuecheng.mapper.CoursePublishMapper;
import com.xuecheng.mapper.CoursePublishPreMapper;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import com.xuecheng.model.dto.CourseBaseInfoDto;
import com.xuecheng.model.dto.CoursePreviewDto;
import com.xuecheng.model.dto.TeachplanDto;
import com.xuecheng.model.po.*;
import com.xuecheng.service.CourseBaseInfoService;
import com.xuecheng.service.CoursePublishPreService;
import com.xuecheng.service.CoursePublishService;
import com.xuecheng.service.TeachplanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author 小班哥
 * @since 2023-04-15
 */
@Service
public class CoursePublishPreServiceImpl extends ServiceImpl<CoursePublishPreMapper, CoursePublishPre> implements CoursePublishPreService {

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseBaseInfoService courseBaseInfoService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    private CoursePublishMapper coursePublishMapper;

    @Autowired
    private CourseBaseMapper courseBaseMapper;


    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 提交课程审核
     * @param companyId 机构ID
     * @param courseId 课程ID
     */

    @Transactional
    @Override
    public void commitAudit(long companyId, long courseId) {
        //查询课信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        if (courseBaseInfo == null)
        {
            throw new XueChengPlusException("找不到该课程");
        }
        //本机构只允许提交本机构的课程
        if (!courseBaseInfo.getCompanyId().equals(companyId)){
            throw new XueChengPlusException("本机构只允许提交本机构的课程");
        }
        //审核状态为已提交则不允许重复提交
        if (courseBaseInfo.getAuditStatus().equals("202003")) {
            throw new XueChengPlusException("课程一提交,请等待审核");
        }
        //课程图片如果为空，则不允许提交
        if (!StringUtils.isNotEmpty(courseBaseInfo.getPic())) {
            throw new XueChengPlusException("请上传课程的封面图片");
        }
        //没有添加课程计划不允许提交审核
        List<TeachplanDto> teachplayTree = teachplanService.findTeachplayTree(courseId);
        if (teachplayTree == null || teachplayTree.size() == 0){
            throw new XueChengPlusException("请编写课程计划");
        }


        //提交审核
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfo , coursePublishPre);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        String MarketJson = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(MarketJson);
        String TeachersJSON = JSON.toJSONString(teachplayTree);
        coursePublishPre.setTeachers(TeachersJSON);
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCreateDate(LocalDateTime.now());
        CoursePublishPre selectById = coursePublishPreMapper.selectById(courseId);
        int index ;
        if (selectById == null){
            index = coursePublishPreMapper.insert(coursePublishPre);
        }else {
            index = coursePublishPreMapper.updateById(coursePublishPre);
        }
        //更新课程基本信息表的审核状态
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseBase::getId , courseId);
        CourseBase courseBase = new CourseBase();
        courseBase.setAuditStatus("202003");
        int update = courseBaseMapper.update(courseBase, lambdaQueryWrapper);
        if (index <= 0 || update <= 0){
            throw new XueChengPlusException("提交审核失败");
        }

    }

    /**
     * 课程发布
     * @param companyID 机构ID
     * @param courseID 课程ID
     */
    @Transactional
    @Override
    public void PublishCourse(long companyID, long courseID) {
        //查询预发布表是否存在
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseID);
        if (coursePublishPre == null){
            throw new XueChengPlusException("课程未提交审核");
        }
        if (!"202004".equals(coursePublishPre.getStatus())){
            throw new XueChengPlusException("课程未审核通过");
        }
        if (!coursePublishPre.getCompanyId().equals(companyID)){
            throw new XueChengPlusException("本机构只允许发布本机构的课程");
        }

        CoursePublish selectById = coursePublishMapper.selectById(courseID);
        CoursePublish coursePublish = new CoursePublish();
        //查询发布表是否存在数据，如果存在则更新
        BeanUtils.copyProperties(coursePublishPre , coursePublish);
        coursePublish.setStatus("203002");
        if (selectById == null){
            coursePublishMapper.insert(coursePublish);
        }else {
            coursePublishMapper.updateById(coursePublish);
        }

        //更新课程基本信息表的发布状态
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseBase::getId , courseID);
        CourseBase courseBase = new CourseBase();
        courseBase.setStatus("203002");
        courseBaseMapper.update( courseBase, lambdaQueryWrapper);

        //向消息表写入数据
        SaveCoursePublishMessage(courseID);

        //删除预发布表的数据
        coursePublishPreMapper.deleteById(courseID);
    }

    /**
     *  保存消息记录
     * @param courseID 课程ID
     */
    private void SaveCoursePublishMessage(long courseID){
        MqMessage course_publish = mqMessageService.addMessage("course_publish", String.valueOf(courseID), null, null);
        if (course_publish == null){
            XueChengPlusException.cate("");
        }
    }
}
